import React from 'react'
import {connect,} from 'react-redux'

import {Modal, WhiteSpace} from "antd-mobile"
import PopupLayout from "../PopupLayout/PopupLayout"
import GiftPopupTab from "./GiftPopupTab/GiftPopupTab"
import GiftList from "./GiftList/GiftList"
import GiftPopupBtns from "./GiftPopupBtns/GiftPopupBtns"
import GiftCount from "./GiftCount/GiftCount"

import {getMyGiftReq, getUserDetailReq} from "../../../../../../apis/goApis";

import RoundGiftIcon from "../../../../../../res/images/web/chat-room/Gift2@2x.png"
import LocalStorageService from "../../../../../../utils/LocalStorageService";
import constants from "../../../../../../utils/constants";
const storage = LocalStorageService

class GiftPopup extends React.Component {

    constructor(props) {
        super(props)
        this.uid = storage.get('userid')
        this.state = {
            tabs: [
                {title: '礼物', active: true,},
                {title: '装备包', active: false,},
            ],
            curIndex: 0,
            curTab: {title: '礼物', active: true,},
            list: [],
            myGiftList: [],
            total: 0,
            selectGift: null,
            giftSend: false,
            gold: 0,
        }
    }

    componentDidMount() {

        if (this.uid) {
            this.getUserDetail()
                .then(() => {
                    this.getGift()
                })
        }

    }

    getUserDetail = () => {
        // return this.props.fetchUserDetail({uid: this.uid,})
        return getUserDetailReq({uid: this.uid,}, false,)
            .then((resp) => {
                if (resp.data.ok) {
                    this.setState({
                        gold: resp.data.ok.Gold,
                    })
                }
            })
    }

    getGift = () => {
        getMyGiftReq({
            uid: this.uid,
        }).then((resp) => {
            if (resp && resp.data && resp.data.prop) {
                const data = resp.data
                const list = data.prop.sort((g1, g2) => g1.Gold - g2.Gold)
                let myGiftList = []
                if (data && data.packet) {
                    [...data.packet].map(gift => {
                        let giftData = list.find(g => g.Id === gift[0])
                        if (giftData && gift[1] > 0) {
                            myGiftList.push({
                                ...giftData,
                                count: gift[1],
                            })
                        }
                    })
                }
                if (list.length > 0) {
                    list[0].selected = true
                }

                if (myGiftList.length > 0) {
                    myGiftList[0].selected = true
                }


                this.setState({
                    list,
                    myGiftList,
                    selectGift: list[0],
                    total: 1,
                }, () => {
                    if (myGiftList.length > 0) {
                        this.setState({
                            tabs: [
                                {title: '礼物', active: false,},
                                {title: '装备包', active: true,},
                            ],
                            curTab: {title: '装备包', active: true,},
                            curIndex: 1,
                            selectGift: myGiftList[0],
                        })
                    }
                })
            }
        })
    }

    onTabClick = (tab) => {
        const tabs = this.state.tabs
        const curIndex = tabs.findIndex(t => t.title === tab.title)
        tabs.forEach((tab, index) => {
            tab.active = index === curIndex
        })
        const list = this.state.list.map((g, i,) => {
            g.selected = i === 0
            return g
        })
        const myGiftList = this.state.myGiftList.map((g, i,) => {
            g.selected = i === 0
            return g
        })
        this.setState({
            tabs: [...tabs,],
            curIndex,
            curTab: tab,
            selectGift: curIndex === 0 ? this.state.list[0] : this.state.myGiftList[0],
            list: [...list,],
            myGiftList: [...myGiftList,],
        })
        // this.setState({
        //     tabs: [...tabs,],
        //     curIndex,
        //     curTab: tab,
        // }, () => {
        //     this.initState()
        // })
    }

    onGiftSelected = (gift) => {
        const isList = this.state.curIndex === 0
        const list = isList ? this.state.list : this.state.myGiftList
        const selectIndex = list.findIndex(g => g.Id === gift.Id)
        list.forEach((gift, index) => {
            gift.selected = index === selectIndex
        })
        if (isList) {
            this.setState({
                list,
                selectGift: gift,
            })
        } else {
            this.setState({
                myGiftList: list,
                selectGift: gift,
            })
        }
    }

    changeTotal = offset => {
        const result = this.state.total + offset
        if (result <= 0) {
            this.setState({
                total: 0,
            })
        } else {
            this.setState({
                total: result,
            })
        }
    }

    giveModalAlert = () => {
        const btnList = [
            { text: <span>否</span>, onPress: () => {} },
            {
                text: <span>是</span>,
                onPress: () => this.giveConfirm(),
            },
            // {}
        ]
        Modal.alert('是否确认支付', '', btnList)
    }

    giveConfirm = () => {
        const selectedItem = this.state.selectGift
        selectedItem.giftnum = this.state.total
        const UsePack = this.state.tabs[1].active
        selectedItem.UsePack = UsePack
        this.props.onSendGift(selectedItem).then(() => {
            this.setState({
                giftSend: true,
            }, () => this.onPopClose('gift'))
        })
    }

    onPopClose = (key) => {
        // this.initState()
        const giftSend = this.state.giftSend
        const select = this.state.selectGift
        if (select) {
            this.getGift()
            if (giftSend) {
                this.getUserDetail()
            }
        }
        this.props.onClose(key)
    }

    // initState = () => {
    //     this.setState({
    //         total: 0,
    //         selectGift: null,
    //     })
    // }

    render() {
        const {
            // userDetail: {Gold,},
            visible,
            onClose,
        } = this.props
        const Gold = this.state.gold
        const list = this.state.list
        const packet = this.state.myGiftList
        const currentTab = this.state.curTab
        const showGiftList = currentTab.title === '礼物'
        const total = this.state.total
        const selectGift = this.state.selectGift
        let confirmClickable = selectGift && total >= 1

        const template = (
            <PopupLayout
                popup
                visible={visible}
                afterClose={this.props.afterClose}
                // onClose={() => this.onPopClose('gift')}
                onClose={() => this.props.onClose('gift')}
                animationType="slide-up"
                iconUrl={RoundGiftIcon}
                Gold={Gold}
            >
                <GiftPopupTab
                    tabs={this.state.tabs}
                    onTabSelected={this.onTabClick}
                />
                <div
                    style={{
                        background: '#F8F8F8',
                    }}
                >
                    <GiftList
                        showData={showGiftList ? list : packet}
                        onGiftSelected={this.onGiftSelected}
                    />
                    <div style={{padding: '16px',}}>
                        <GiftCount
                            changeTotal={this.changeTotal}
                            total={this.state.total}
                        />
                        <WhiteSpace size='xl'/>
                        <GiftPopupBtns
                            giveConfirm={this.props.fromPlan ? () => this.giveModalAlert() : () => this.giveConfirm()}
                            onClose={onClose}
                            confirmClickable={confirmClickable}
                        />
                    </div>
                </div>

            </PopupLayout>
        )

        return template
    }
}


const mapDispatchToProps = (dispatch) => ({
    fetchUserDetail: (id) => dispatch.user.fetchUserDetail(id),
})

export default connect(null, mapDispatchToProps)(GiftPopup)
